import rclpy
from patrol_interfaces.srv import SpeechText
from rclpy.node import Node
import espeakng

class SpeakNode(Node):
    def __init__(self,name):
        super().__init__(name)
        self.peak_srv_=self.create_service(SpeechText,'speech_text',self.speechtext_callback)       #创建一个服务器对象，订阅speech_text话题，收到客户端请求触发
        self.speaker_=espeakng.Speaker()                                                            #实例化Speaker
        self.speaker_.voice='zh'                                                                    #设置语言为中文
    
    def speechtext_callback(self,request,response):
        self.get_logger().info(f'正在准备朗读{request.text}')                                          
        self.speaker_.say(request.text)                                                         #传入客户端请求进行朗读    
        self.speaker_.wait()                                                                    #等待文字朗读完毕
        response.result=True                                                                    #语音合成成功标志置一
        return response
    
def main(args=None):
    rclpy.init(args=args)
    node=SpeakNode('speaker')                                                               #实例化SpeakNode
    rclpy.spin(node)                                                                        #阻塞等待node运行
    node.destroy_node()
    rclpy.shutdown()                                                                        #关闭服务
        